#include "io_driver.h"
#include <board.h>
#include <rtdevice.h>

/* 假设的GPIO引脚定义，需要根据实际硬件连接修改 */
static const rt_uint16_t input_pins[DIGITAL_INPUT_CHANNELS] = {
    GET_PIN(A, 0),  GET_PIN(A, 1),  GET_PIN(A, 2),  GET_PIN(A, 3),
    GET_PIN(A, 4),  GET_PIN(A, 5),  GET_PIN(A, 6),  GET_PIN(A, 7),
    GET_PIN(B, 0),  GET_PIN(B, 1),  GET_PIN(B, 2),  GET_PIN(B, 3)
};

static const rt_uint16_t output_pins[DIGITAL_OUTPUT_CHANNELS] = {
    GET_PIN(C, 0),  GET_PIN(C, 1),  GET_PIN(C, 2),  GET_PIN(C, 3),
    GET_PIN(C, 4),  GET_PIN(C, 5),  GET_PIN(C, 6),  GET_PIN(C, 7),
    GET_PIN(C, 8),  GET_PIN(C, 9),  GET_PIN(C, 10), GET_PIN(C, 11)
};

rt_err_t io_driver_init(void)
{
    /* Initialize input GPIOs */
    for (int i = 0; i < DIGITAL_INPUT_CHANNELS; i++) {
        rt_pin_mode(input_pins[i], PIN_MODE_INPUT_PULLUP);
    }

    /* Initialize output GPIOs */
    for (int i = 0; i < DIGITAL_OUTPUT_CHANNELS; i++) {
        rt_pin_mode(output_pins[i], PIN_MODE_OUTPUT);
        rt_pin_write(output_pins[i], PIN_LOW);
    }

    return RT_OK;
}

rt_bool_t io_read_input(uint8_t channel)
{
    if (channel >= DIGITAL_INPUT_CHANNELS) {
        return RT_FALSE;
    }

    return (rt_pin_read(input_pins[channel]) == PIN_HIGH) ? RT_TRUE : RT_FALSE;
}

rt_err_t io_set_output(uint8_t channel, rt_bool_t state)
{
    if (channel >= DIGITAL_OUTPUT_CHANNELS) {
        return RT_ERR_PARAM;
    }

    rt_pin_write(output_pins[channel], state ? PIN_HIGH : PIN_LOW);
    return RT_OK;
}

rt_bool_t io_get_output_state(uint8_t channel)
{
    if (channel >= DIGITAL_OUTPUT_CHANNELS) {
        return RT_FALSE;
    }

    return (rt_pin_read(output_pins[channel]) == PIN_HIGH) ? RT_TRUE : RT_FALSE;
}